package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.attendance.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.entity.ExcelMember;
import com.nineclock.system.entity.ExcelMemberListener;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SysCompanyUserService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysCompanyUserServiceImpl implements SysCompanyUserService {
    @Autowired
    SysCompanyUserMapper companyUserMapper;
    @Autowired
    SysDepartmentMapper departmentMapper;

    @Override
    public List<SysCompanyUserDTO> queryCompanyMemberList() {
        //1.获取企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //查询当前企业的员工列表
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId,companyId);
        wrapper.eq(SysCompanyUser::getEnable,1);

        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(wrapper);
        //如果不为null,转换为dto, 并返回
       if (CollectionUtil.isNotEmpty(companyUserList)){
           List<SysCompanyUserDTO> companyUserDTOList = BeanHelper.copyWithCollection(companyUserList, SysCompanyUserDTO.class);
           return companyUserDTOList;
       }

        return null;
    }

    @Override
    public PageResult<SysCompanyUserDTO> members(Integer page, Integer pageSize, String keyword, Long departmentId) {
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        //keyword 关键词 模糊查询
        if (keyword!=null) {
            wrapper.and(wrapper1->{
                wrapper1.like(SysCompanyUser::getUserName,keyword)
                        .or().like(SysCompanyUser::getWorkNumber,keyword)
                        .or().like(SysCompanyUser::getMobile,keyword);
            });

        }

        //departmentId 查询该部门的员工信息, 查询该部门的子部门id集合
        List<Long> ids = new ArrayList<>();
        if (departmentId != 0){
            ids.add(departmentId);
        }


        //查询子部门id
        this.queryChildDepartmentIds(ids,departmentId);
        wrapper.in(SysCompanyUser::getDepartmentId,ids);

        //创建page对象
        Page<SysCompanyUser> companyUserPage = new Page<>(page,pageSize);
        //分页查询
        companyUserPage = companyUserMapper.selectPage(companyUserPage, wrapper);

        //获取数据列表
        List<SysCompanyUser> records =  companyUserPage.getRecords();

        return new PageResult(
                companyUserPage.getTotal(),
                companyUserPage.getPages(),
                BeanHelper.copyWithCollection(records, SysCompanyUserDTO.class));
    }
    @Autowired
    SysCompanyUserRoleMapper companyUserRoleMapper;
    @Autowired
    SysRoleMapper roleMapper;

    @Override
    public void importDate(MultipartFile excelFile) throws IOException {
        //先对excel内容进行解析 然后存放到数据库中
        //1.读取数据                                                                //这个 this 就是 companyUserService
                                                                                    //这个里面有 传过来的文件excelFile
                                                                                    //this代表的就是companyUserService的实现类
        EasyExcel.read(excelFile.getInputStream(),ExcelMember.class, new ExcelMemberListener(this))
                .sheet(0)
                .doRead();

    }
    @Autowired
    SysUserMapper userMapper;

    @Override
    public void handleParseDate(List<ExcelMember> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            //查询数据库中的手机号和邮箱有没有被注册过
            for (ExcelMember excelMember : list) {
                //判断手机号和邮箱是否唯一
                LambdaQueryWrapper<SysUser> userQw = new LambdaQueryWrapper<>();
                //以下判断条件 相当于 where id = 1
                userQw.eq(SysUser::getMobile,excelMember.getMobile())
                        .or().eq(SysUser::getEmail,excelMember.getEmail());

                Integer count = userMapper.selectCount(userQw);
                if (count > 0) {
                    throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
                }
                //判断工号 是否唯一
                LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
                companyUserQw.eq(SysCompanyUser::getWorkNumber,excelMember.getWorkNumber());
                companyUserQw.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());

                Integer count1 = companyUserMapper.selectCount(companyUserQw);
                if (count1 > 0) {
                    throw  new NcException(ResponseEnum.WROK_NUM_EXISTS);
                }

                //保存用户信息到数据库
                SysUser user = new SysUser();
                user.setUsername(excelMember.getName());
                user.setMobile(excelMember.getMobile());
                user.setEmail(excelMember.getEmail());
                user.setPassword(new BCryptPasswordEncoder().encode("123456"));
                user.setStatus((short)1);
                user.setCreateTime(new Date());
                user.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());

                userMapper.insert(user);

                SysCompanyUser companyUser = new SysCompanyUser();
                companyUser.setUserId(user.getId());
                companyUser.setUserName(excelMember.getName());
                companyUser.setMobile(excelMember.getMobile());

                //设置部门信息  先查  再存
                if (StrUtil.isNotEmpty(excelMember.getDepartmentName())) {
                    //根据部门名称,先查询对应的部门信息
                    LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
                    departmentQw.eq(SysDepartment::getName,excelMember.getDepartmentName());
                    departmentQw.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());

                    SysDepartment department = departmentMapper.selectOne(departmentQw);
                    if (department != null) {
                        companyUser.setDepartmentId(department.getId());
                        companyUser.setDepartmentName(department.getName());
                    }
                }



                companyUser.setPost(excelMember.getPosition());
                companyUser.setWorkNumber(excelMember.getWorkNumber());
                companyUser.setEmail(excelMember.getEmail());
                companyUser.setOfficeAddress(excelMember.getWorkAddr());
                companyUser.setRemark(excelMember.getDesc());
                companyUser.setTimeEntry(excelMember.getEntryTime());
                companyUser.setEnable((short) ("可用".equals(excelMember.getEnable()) ? 1 : 0 ));

                //新增员工
                companyUserMapper.insert(companyUser);

                //维护角色表和角色的中间表
                //根据角色名称 查询角色对象
                LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
                roleQw.eq(SysRole::getCompanyId,CurrentUserHolder.get().getCompanyId());
                roleQw.eq(SysRole::getRoleDesc,excelMember.getRoleName());

                SysRole role = roleMapper.selectOne(roleQw);
                if (role != null) {
                    SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
                    companyUserRole.setCompanyUserId(companyUser.getId());
                    companyUserRole.setCompanyId(CurrentUserHolder.get().getCompanyId());
                    companyUserRole.setRoleId(role.getId());
                    //保存员工和角色的关系
                    companyUserRoleMapper.insert(companyUserRole);
                }







            }
        }
    }

    @Override
    public SysCompanyUserDTO queryOne(String mobile) {
        if (mobile==null) {
            throw  new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getMobile,mobile);
        wrapper.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());

        SysCompanyUser companyUser = companyUserMapper.selectOne(wrapper);

        if (companyUser != null) {
            return BeanHelper.copyProperties(companyUser,SysCompanyUserDTO.class);
        }

        return null;
    }

    @Override
    public Integer queryUserCountByDepartmentIds(List<Long> departmentIds) {
        List<Long> ids = new ArrayList<>();
        ids.addAll(departmentIds);
        //查询这些部门的子部门信息
        if (departmentIds != null) {
            for (Long departmentId : departmentIds) {
                this.queryChildDepartmentIds(ids,departmentId);
//                LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
//                departmentQw.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
//                departmentQw.eq(SysDepartment::getParentId,departmentId);
//                List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);
//                if (CollectionUtil.isNotEmpty(departmentList)) {
//                    List<Long> ids = departmentList.stream().map(department -> {
//                        return department.getId();
//                    }).collect(Collectors.toList());
//                }
            }
        }
        //统计员工的数量
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
//        if (ids.size() != 0){
            wrapper.in(SysCompanyUser::getDepartmentId,ids);
//        }

        //判断员工 所在部门是否在集合中
        Integer  count =  companyUserMapper.selectCount(wrapper);
        return count;
    }


    /**
     *查询 指定部门的 下级部门及员工信息
     * @param departmentId
     * @param includeMember
     * @return
     */

    @Override
    public List<DepartmentOrUserSimpleDTO> querySimpleDepartment(Long departmentId, Integer includeMember) {

        List<DepartmentOrUserSimpleDTO> departmentOrUserSimpleDTOList = new ArrayList<>();

        //健壮性判断
        if (departmentId == null || includeMember == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //先查询 下级部门信息
        LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
        departmentQw.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        departmentQw.eq(SysDepartment::getParentId,departmentId);

        //查询获取下级部门列表
        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);
        if (CollectionUtil.isNotEmpty(departmentList)){
            for (SysDepartment department : departmentList) {
                //转换为simple对象
                DepartmentOrUserSimpleDTO departmentSimpleDTO = new DepartmentOrUserSimpleDTO();
                departmentSimpleDTO.setId(department.getId());
                departmentSimpleDTO.setName(department.getName());
                departmentSimpleDTO.setType(1); //类型为部门

                departmentOrUserSimpleDTOList.add(departmentSimpleDTO);
            }
        }

        //查询员工列表
        if (includeMember == 0) {
            LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
            companyUserQw.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
            companyUserQw.eq(SysCompanyUser::getDepartmentId,departmentId);

            //查询获取该部门的员工信息
            List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserQw);

            if (CollectionUtil.isNotEmpty(companyUserList)) {
                for (SysCompanyUser companyUser : companyUserList) {
                    DepartmentOrUserSimpleDTO userSimpleDTO = new DepartmentOrUserSimpleDTO();
                    userSimpleDTO.setId(companyUser.getId());
                    userSimpleDTO.setName(companyUser.getUserName());
                    userSimpleDTO.setType(2);

                    //添加到集合中
                    departmentOrUserSimpleDTOList.add(userSimpleDTO);
                }
            }
        }



        return departmentOrUserSimpleDTOList;
    }





    private void queryChildDepartmentIds(List<Long> ids, Long departmentId) {
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId,departmentId);

        //子部门列表
        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);

        if (CollectionUtil.isNotEmpty(departmentList)) {
            //把部门列表集合转换为 部门id集合
            List<Long> departmentIds = departmentList.stream().map(department ->{
                return department.getId();
            }).collect(Collectors.toList());
            //把部门id 添加到集合中
            ids.addAll(departmentIds);

            //循环部门id,再次查询子部门
            for (Long id : departmentIds) {
                this.queryChildDepartmentIds(ids,id);
            }
        }
    }
}
